<?php
session_start();
// 数据库连接配置
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: ". $conn->connect_error);
}

// 查询聊天记录，这里获取近一年的聊天记录，你可以根据需求修改查询条件
$sql = "SELECT u.username, cr.message 
        FROM chat_records cr
        JOIN users u ON cr.user_id = u.id
        WHERE cr.send_time >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)";

// 如果是私聊，只返回双方的聊天记录
if (isset($_GET["private"]) && isset($_GET["from"]) && isset($_GET["to"])) {
    $from = $_GET["from"];
    $to = $_GET["to"];
    $sql.= " AND ( (cr.user_id = $from AND (SELECT user_id FROM private_chats WHERE from_user = $from AND to_user = $to)) 
                OR (cr.user_id = $to AND (SELECT user_id FROM private_chats WHERE from_user = $to AND to_user = $from)) )";
}

$result = $conn->query($sql);

$messages = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $messages[] = $row;
    }
}

// 将聊天记录以 JSON 格式返回给前端
echo json_encode($messages);

$conn->close();
?>
